package com.barradata.app0624.modules.web

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Vibrator
import android.view.MotionEvent
import android.view.View
import android.webkit.*
import android.webkit.WebSettings.LOAD_NO_CACHE
import com.barradata.BuildConfig
import com.barradata.R
import com.barradata.app0624.api.ApiService
import com.barradata.app0624.config.Constant
import com.barradata.app0624.data.UserDataManager
import com.barradata.app0624.modules.bankcard.BankAuthActivity
import com.barradata.app0624.modules.contact.ContactActivity2
import com.barradata.app0624.modules.extra.ExtraInfoActivity
import com.barradata.app0624.modules.idcard.IdCardActivity
import com.barradata.app0624.modules.login.LoginActivity
import com.barradata.app0624.modules.protocol.LoanProtocolActivity
import com.barradata.common.base.BaseActivity
import com.barradata.common.rxbinding.clickV
import com.barradata.common.rxbus.RxBus
import com.barradata.common.utils.ToastUtils
import com.barradata.common.view.AlertDialogFragment
import com.example.hfiveandaplication.utils.ApkUtils
import com.example.hfiveandaplication.utils.LocationUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.web_activity.*


/**
 * Author:    WuNan
 * Email:     wunan@barradata.com
 * Created:   2019/7/4 10:54
 **/
class WebActivity : BaseActivity() {

    companion object {
        fun actionStart(context: Context) {
            context.startActivity(Intent(context, WebActivity::class.java))
        }

        private val REQUEST_PERMISSION = arrayOf(
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
    }

    override fun getLayoutId() = R.layout.web_activity

    private val rxPermissions = RxPermissions(this)

    override fun initView() {
        setupWebView()
        setupDebugButtons()
        registerLoginCallback()
    }

//    override fun onResume() {
//        super.onResume()
//        setupGoogleUpdateDIalog()
//    }

    private fun setupGoogleUpdateDIalog() {
        ApiService.getGooglePlayUpdateInfo().subscribe({ response ->
            if (response.isRel) {
                if (response.data.url.isNotEmpty() && response.data.appVersion.isNotEmpty()
                        && response.data.desc.isNotEmpty() && response.data.mD5.isNotEmpty()) {
                    AlertDialogFragment.create({
                        ApkUtils.launchAppDetail(this, response.data.getpName())
                    }, null)
                            .setTitle(R.string.checkout_new_version)
                            .setContent(getString(R.string.checkout_new_version) + ":${response.data.appVersion}\n${response.data.desc}")
                            .setCancelAble(response.data.isUpdate)
                            .show(this)
                }
            }
        }, {
            logD(it.message.toString())
        }).autoClean()
    }

    private fun setupDebugButtons() {
        if (!BuildConfig.DEBUG) {
            return
        }
        var lastX = 0
        var lastY = 0
        var clickedTimestamp = 0L
        debug_button.visibility = View.VISIBLE
        debug_button.setOnTouchListener { v, it ->
            when (it.action) {
                MotionEvent.ACTION_DOWN -> {
                    lastX = it.x.toInt()
                    lastY = it.y.toInt()
                    clickedTimestamp = System.currentTimeMillis()
                }
                MotionEvent.ACTION_MOVE -> {
                    val offsetX = it.x.toInt() - lastX
                    val offsetY = it.y.toInt() - lastY
                    v.apply {
                        layout(left + offsetX, top + offsetY, right + offsetX, bottom + offsetY)
                    }
                }
                MotionEvent.ACTION_UP -> {
                    if ((System.currentTimeMillis() - clickedTimestamp) < 100) {
                        v.performClick()
                    }
                }
            }
            true
        }

        debug_button.clickV().subscribe {
            ToastUtils.showShort("退出登录")
            UserDataManager.clear()
            web_view.clearFormData()
            web_view.clearCache(true)
            web_view.clearHistory()
            web_view.loadUrl("javascript:removeToken()")
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                CookieManager.getInstance().removeAllCookies {}
            } else {
                CookieManager.getInstance().removeAllCookie()
            }
            web_view.reload()
        }.autoClean()
    }

    private fun registerLoginCallback() {
        RxBus.toObservable(WebCallbackEvent::class.java).subscribe {
            dispatchWebCallbackEvent(it.eventType)
        }.autoClean()
    }

    override fun onBackPressed() {
        if (web_view.canGoBack()) {
            web_view.goBack()
        } else {
            super.onBackPressed()
        }
    }


    @SuppressLint("SetJavaScriptEnabled")
    private fun setupWebView() {
        web_view.addJavascriptInterface(this, "HomeFragment")
        web_view.settings.javaScriptEnabled = true
        web_view.settings.javaScriptCanOpenWindowsAutomatically = true
        web_view.settings.cacheMode = LOAD_NO_CACHE
        web_view.webViewClient = object : WebViewClient() {
            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
                showLoadingView()
            }

            override fun onPageFinished(view: WebView, url: String) {
                super.onPageFinished(view, url)
                dismissLoadingView()
                logD("url: $url")
            }

        }
        web_view.webChromeClient = object : WebChromeClient() {
            override fun onJsAlert(view: WebView?, url: String?, message: String?, result: JsResult?): Boolean {
                logD("alert : $message")
                ToastUtils.showShort(message.toString())
                result?.confirm()
                return true
            }
        }
        web_view.loadUrl(Constant.H5_URL)
    }

    @JavascriptInterface
    fun loginEvent() {
        startActivity(Intent(this, LoginActivity::class.java))
    }

    @JavascriptInterface
    fun clickPhoneEvent(phoneNumber: String) {
        logD("phone: $phoneNumber")
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse("tel:$phoneNumber"))
        startActivity(intent)
    }

    @JavascriptInterface
    fun bankCardAuthEvent() {
        BankAuthActivity.actionStart(this)
    }

    @Deprecated("单词拼写错误，待琪红同步修改后废弃此函数")
    @JavascriptInterface
    fun addtionalAuthEvent() {
        ExtraInfoActivity.actionStart(this)
    }

    @JavascriptInterface
    fun additionalAuthEvent() {
        ExtraInfoActivity.actionStart(this)
    }

    @JavascriptInterface
    fun idcardAuthEvent() {
        IdCardActivity.actionStart(this)
    }

    @JavascriptInterface
    fun contactAuthEvent() {
        ContactActivity2.actionStart(this)
    }

    @JavascriptInterface
    fun vibrateEvent() {
        val vibrator = getSystemService(VIBRATOR_SERVICE) as Vibrator
        vibrator.vibrate(1000)
    }

    @JavascriptInterface
    fun logoutEvent() {
        UserDataManager.clear()
    }

    @JavascriptInterface
    fun createOrderEvent(pid: String, expiryReturned: String) {
        runOnUiThread {
            if (checkPermission()) {
                ApiService.getStatus().filter { it.status == 200 }.subscribe({
                    if (it.status == 200) {
                        createOrder(pid, expiryReturned, it.data.addressBookUuid)
                        uploadLocationInfo()
                    } else {
                        ToastUtils.showShort(it.message)
                    }
                }, {
                    ToastUtils.showShort(R.string.network_error)
                }).autoClean()
            }
        }
    }

    @JavascriptInterface
    fun loanProtocolEvent(money: String, period: String) {
        LoanProtocolActivity.actionStart(this, money, period)
    }

    @JavascriptInterface
    fun killAppEvent() {
        finish()
    }

    private fun createOrder(pid: String, expiryReturned: String, addressBookUuid: String) {
        UserDataManager.addressBookUuid = addressBookUuid
        ApiService.createOrder(pid, expiryReturned, addressBookUuid).subscribe({
            if (it.status == 200) {
                web_view.loadUrl("javascript:togoSubmit(200)")
            } else {
                ToastUtils.showShort(it.message)
                web_view.loadUrl("javascript:togoSubmit(\"${it.message}\")")
            }
        }, {
            ToastUtils.showShort(R.string.network_error)
        }).autoClean()
    }

    private fun uploadLocationInfo() {
        ApiService.uploadLocationInfo(LocationUtils.getLocation(this)).subscribe({
            logD(it.message)
        }, {
            logD(it.message.toString())
        }).autoClean()
    }

    private fun checkPermission(): Boolean {
        REQUEST_PERMISSION.iterator().forEach {
            if (!rxPermissions.isGranted(it)) {
                requestPermission()
                return false
            }
        }
        return true
    }

    private fun requestPermission() {
        rxPermissions.requestEachCombined(*REQUEST_PERMISSION).subscribe {
            if (it.granted) {
                return@subscribe
            }
            val ensureButtonAction: () -> Unit
            if (it.shouldShowRequestPermissionRationale) {
                ensureButtonAction = { requestPermission() }
            } else {
                ensureButtonAction = { go2Setting() }
            }
            ToastUtils.showShort(R.string.get_permission_failure_hint)
            AlertDialogFragment.create(ensureButtonAction, null)
                    .setTitle(getString(R.string.get_permission_failure_hint))
                    .show(this)
        }.autoClean()
    }

    private fun go2Setting() {
        val localIntent = Intent()
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        localIntent.action = "android.settings.APPLICATION_DETAILS_SETTINGS"
        localIntent.data = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null)
        startActivity(localIntent)
    }


    private fun dispatchWebCallbackEvent(eventType: EventType) {
        when (eventType) {
            EventType.FROM_CANCEL -> {
                if (web_view.url != Constant.H5_URL_HOME) {
                    web_view.loadUrl(Constant.H5_URL)
                }
            }
            EventType.FROM_LOGIN -> {
                val token = UserDataManager.token
                val uuid = UserDataManager.uuid
                if (token.isNotEmpty() && uuid.isNotEmpty()) {
                    logD("appGetToken token: $token  uuid: $uuid")
                    web_view.loadUrl("javascript:appGetToken(\"$token\",\"$uuid\")")
                }
            }
            EventType.FROM_IDCARD -> {
                web_view.loadUrl("javascript:togoPersonInfo()")
            }
            EventType.FROM_BANK -> {
                ExtraInfoActivity.actionStart(this)
            }
            EventType.FROM_EXTRA_INFO -> {
                if (web_view.url != Constant.H5_URL_HOME) {
                    web_view.loadUrl(Constant.H5_URL)
                }
            }
            EventType.FROM_CONTACT -> {
                BankAuthActivity.actionStart(this)
            }
        }
    }
}